import React from 'react';
import BpmnEditor from 'components/bpmnEditor/BpmnEditor';
import { message, Card, Button } from 'antd';
import { modifyProcess, inquiryProcess } from 'services/process';
import { defaultRejectHandler } from 'utils/http';

export default class BpmnModifier extends React.Component {
  componentDidMount() {
    const { props: { processId }, bpmnEditor } = this;
    inquiryProcess({ params: { processId } }).then((data) => {
      bpmnEditor.init(data.bpmn);
    }, defaultRejectHandler);
  }

  modifyBPMN = () => {
    const { name } = this.props;
    const { saveXML } = this.bpmnEditor;
    saveXML((err, xml) => {
      if (err) {
        console.error('could not save BPMN 2.0 diagram', err);
      }
      const file = new File([xml], name, {
        type: 'text/plain',
      });
      const formData = new FormData();
      formData.append('name', name);
      formData.append('file', file);
      modifyProcess(formData).then(() => {
        message.success('修改成功');
      }, (reason) => {
        console.error(reason);
      });
    });
  }

  render() {
    const { name } = this.props;
    return (
      <Card title={name} style={{ margin: '10px' }}>
        <BpmnEditor ref={(editor) => { this.bpmnEditor = editor; }} />
        <Button
          onClick={this.modifyBPMN}
          type="primary"
          style={{ float: 'right' }}
        >
            提交修改
        </Button>
      </Card>
    );
  }
}
